`var = something rescue nil` behaviour
Posted
by JP
on Stack Overflow
See other posts from Stack Overflow
or by JP
Published on 2010-04-12T11:48:27Z
Indexed on
2010/04/12
11:53 UTC
Read the original article
Hit count: 334
ruby
In ruby you can throw a rescue
at the end of an assignment to catch any errors that might come up. I have a function (below: a_function_that_may_fail
) where it's convenient to let it throw an error if certain conditions aren't met. The following code works well
post = {}
# Other Hash stuff
post['Caption'] = a_function_that_may_fail rescue nil
However I'd like to have post['Caption'] not even set if the function fails.
I know I can do:
begin
post['Caption'] = a_function_that_may_fail
recsue
end
but that feels a little excessive - is there a simpler solution?
© Stack Overflow or respective owner